package com.gaofei.user.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaofei.user.service.TbUserService;
import com.macro.cloud.domain.AccessTokenDto;
import com.macro.cloud.domain.Oauth2ClientUserDto;
import com.macro.cloud.service.Oauth2ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RefreshScope
@RequestMapping("user")
public class UserController {

    @Autowired
    private TbUserService userService;

    @Autowired
    private Oauth2ClientService oauth2ClientService;

    /**
     * 获取引导到登录页面的地址
     * @return
     */
    @RequestMapping("getLoginUrl")
    public String getLoginUrl(){
        return oauth2ClientService.getOauth2CodeUrl();
    }

    /**
     * 自己的认证服务的回调地址
     * @param code
     * @return
     */

    @RequestMapping("myCallback")
    public String myCallback(String code){
        //1.根据code获取token
        AccessTokenDto accessToken = oauth2ClientService.getAccessToken(code);
        System.out.println(accessToken.getAccess_token()); //生成的token
        //2.根据token获取用户信息
        Oauth2ClientUserDto currentUser = oauth2ClientService.getCurrentUser(accessToken);
        return currentUser.getUser_name();
    }

    /**
     * 码云登录的回调
     * @param code
     * @return
     */
    @GetMapping("giteeCallback")
    public Object giteeCallback(String code ){
        HashMap<String, Object> params = new HashMap<>();
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        params.put("client_id", "7fb8c7c5f6061a82c2c43f300657185a20a3b49faad7e39cfa1403505628e3cb");
        params.put("redirect_uri", "http://127.0.0.1:8080/callback");
        params.put("client_secret", "6ca6b97d81855f86b04d87eccf2045457ee3d784c389f7169e7eb56c58bc2750");
        //1.根据授权码获取token
        String respData = HttpUtil.post("https://gitee.com/oauth/token", params);
        JSONObject entries = JSONUtil.parseObj(respData);//将json字符串,转成json对象
        String token = (String) entries.get("access_token"); //获取token
        //2.根据token获取用户信息
        String userInfo = HttpUtil.get("https://gitee.com/api/v5/user?access_token=" + token);
        System.out.println(userInfo);
        return userInfo;
    }

    @GetMapping("list")
    public Page list(){
        return userService.page(new Page<>(1, 5));
    }

    @Value("${name}")
    private String name;
    @GetMapping("hello")
    public String hello(){
        return name;
    }
}
